import React, { useState, useRef, useEffect } from 'react';
import { Button, Select, Popover, Upload, DatePicker, Tooltip, message } from 'antd';
import type { FormInstance } from 'antd';
import { useModel, history } from 'umi';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import TableHint from '@/components/TableHint/Index';
import PopoverContent from '@/components/PopoverContent/Index';
import { formatDate, getDateValue, MsgType, showMsg, isExits, isSupportSticky, isNull } from '@/utils/utils';
import PermissionControl from '@/components/PermissionControl';
import GoodName from '@/components/Select/GoodName';
// @ts-ignore
import Cookies from 'js-cookie';
import { ProFormFieldSet } from '@ant-design/pro-form';
import { DownloadOutlined } from '@ant-design/icons';
import { subtractDays, currentDate } from '@/utils/utils';
import { imgPrefix } from '@/utils/constants';
import Auditing from '@/components/Auditing';
import {
  getStockAdjustList,
  approveAccept,
  approveReject,
  batchApprove,
  downStockAdjustList,
  getGoodsSpecsList
} from '@/services/stock-goods/api';
import { isMobile } from 'react-device-detect';

const ManageTab = (props: ManageTabProps) => {

  const { tab, brandList, classList, goodsList } = props;

  const formRef = useRef<FormInstance>();
  const actionRef = useRef<ActionType>();
  const auditingRef = useRef();

  const downloadAddr = `${imgPrefix}xlsx/批量入库单.xlsx`;
  // 选择的状态
  const [status, setStatus] = useState<string>(isMobile ? 'N' : 'I');
  const [waitNum, setWaitNum] = useState<number>(0);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

  const [loading, setLoading] = useState<boolean>(false);
  const [searchParams, setSearchParams] = useState({});
  const [optLoading, setOptLoading] = useState<boolean>(false);

  const [canDownload, setCanDownload] = useState<boolean>(false);

  const [rejectVisible, setRejectVisible] = useState<boolean>(false);
  const [agreeVisible, setAgreeVisible] = useState<boolean>(false);
  const [line, setLine] = useState<number>(-1);

  const [viewParams, setViewParams] = useState<any>({});
  const [clickRow, setClickRow] = useState(''); // 当前选中的行编号，用于定位颜色

  const [ggList, setGgList] = useState([]); // 规格列表

  const { initialState } = useModel('@@initialState');

  const columns: ProColumns<STOCKGOODSAPI.StockItem>[] = [
    {
      title: '商品分类',
      dataIndex: 'class_id',
      hideInTable: true,
      order: 6,
      valueType: 'select',
      fieldProps: {
        placeholder: '选择商品分类',
        options: classList,
        showSearch: true,
        filterOption: true,
      }
    },
    {
      title: '商品品牌',
      dataIndex: 'brand_id',
      hideInTable: true,
      order: 5,
      valueType: 'select',
      fieldProps: {
        placeholder: '选择商品品牌',
        options: brandList,
        showSearch: true
      }
    },
    {
      title: '商品名称',
      dataIndex: 'goods_id',
      hideInTable: true,
      order: 4,
      valueType: 'select',
      fieldProps: form => ({
        options: goodsList,
        onChange: (value: any) => {
          form.setFieldsValue({ 'spec_id': null });
          if (!value) {
            setGgList([]);
            return;
          }
          fetchGoodsSpecsList(value);
        }
      })
    },
    {
      title: '商品规格',
      dataIndex: 'specs_id',
      hideInTable: true,
      valueType: 'select',
      hideInSearch: isNull(ggList),
      fieldProps: (form, record) => {
        console.log('规格', record, ggList);
        return {
          options: (ggList || []).map(item => {
            return {
              label: item.specs_name,
              value: item.specs_id as string,
            }
          }),
          showSearch: true,
          onChange: (value: any) => {
            console.log('value', value)
            // const specItem = (dataSource[record.rowIndex].specsList || []).find(item => item.specs_id === value);
            // ggChange(specItem, form, record.rowKey);
          }
        }
      }
    },
    {
      title: '记录状态',
      dataIndex: 'status',
      hideInTable: true,
      order: 3,
      formItemProps: { style: { marginBottom: 0 } },
      valueType: 'select',
      valueEnum: {
        N: '审核通过',
        W: '待审核',
        D: '审核拒绝'
      }
    },
    {
      title: '创建时间',
      dataIndex: 'create_date',
      hideInTable: true,
      order: 1,
      formItemProps: { style: { marginBottom: 0 } },
      renderFormItem: () => {
        return <ProFormFieldSet >
          <DatePicker allowClear={false} style={{ width: '100%' }} />
          <span style={{ padding: '0 5px' }}>-</span>
          <DatePicker allowClear={false} style={{ width: '100%' }} />
        </ProFormFieldSet>
      }
    },
    {
      title: '批次号',
      dataIndex: 'batch_id',
      width: 90,
      search: false
    },
    {
      title: '调整系数',
      dataIndex: 'ratio',
      width: 60,
      search: false,
      hideInTable: initialState?.currentUser?.dept_type !== 'Y'
    },
    {
      title: '操作类型',
      dataIndex: 'oper_type',
      search: false,
      width: 60,
      valueType: 'select',
      valueEnum: {
        I: '商品入库',
        D: '库存调整',
        R: '库存退回',
        B: '库存批量调整'
      }
    },
    {
      title: '数量',
      dataIndex: 'inventory',
      align: 'right',
      width: 40,
      search: false
    },
    {
      title: '状态',
      dataIndex: 'status',
      search: false,
      width: 60,
      valueType: 'select',
      valueEnum: {
        N: '审核通过',
        W: '待审核',
        D: '审核拒绝'
      }
    },
    {
      title: '供应商名称',
      dataIndex: 'supplier',
      formItemProps: { style: { marginBottom: 0 } },
      order: 2,
      width: 80
    },
    {
      title: '商品品牌',
      dataIndex: 'brand_name',
      width: 70,
      search: false
    },
    {
      title: '商品名称',
      dataIndex: 'goods_name',
      width: 70,
      search: false
    },
    {
      title: '商品编号',
      dataIndex: 'goods_id',
      width: 65,
      search: false
    },
    {
      title: '规格编号',
      dataIndex: 'specs_no',
      width: 65,
      className: 'wordbreak',
      search: false
    },
    {
      title: '规格描述',
      dataIndex: 'specs_name',
      ellipsis: true,
      width: 70,
      search: false
    },
    {
      title: '供应商名称',
      dataIndex: 'supplier',
      width: 70,
      search: false
    },
    {
      title: '协议进货价',
      dataIndex: 'agree_price',
      align: 'right',
      valueType: 'money',
      width: 75,
      search: false
    },
    {
      title: '进货折扣',
      dataIndex: 'purchase_discount',
      width: 60,
      align: 'right',
      search: false
    },
    {
      title: '实际进货价',
      dataIndex: 'purchase_price',
      width: 75,
      align: 'right',
      valueType: 'money',
      search: false
    },
    {
      title: '提交时间',
      dataIndex: 'submit_time',
      width: 85,
      search: false
    },
    {
      title: '提交人',
      dataIndex: 'submit_user_name',
      width: 60,
      search: false
    },
    {
      title: '提交说明',
      dataIndex: 'submit_explain',
      width: 70,
      ellipsis: true,
      search: false
    },
    {
      title: '审批时间',
      dataIndex: 'approve_time',
      width: 85,
      search: false
    },
    {
      title: '审批人',
      dataIndex: 'approve_user_name',
      width: 60,
      search: false
    },
    {
      title: '审批说明',
      dataIndex: 'approve_explain',
      ellipsis: true,
      width: 70,
      search: false
    },

    {
      title: '操作',
      // fixed: 'right',
      fixed: isSupportSticky() ? 'right' : '',
      align: 'center',
      width: 125,
      valueType: 'option',
      render: (_, record, index) => {
        if (record.status !== 'W') {
          return [];
        }
        return [
          <PermissionControl key="agree" action_id="200203003">
            <Popover
              visible={agreeVisible && line === index}
              // onVisibleChange={setAgreeVisible}
              content={<PopoverContent
                confirmText="审批通过"
                onCancel={() => {
                  setAgreeVisible(false);
                  setLine(-1);
                }}
                loading={optLoading}
                onConfirm={async (value: string) => {
                  const data = {
                    approval_id: record.approval_id || '',
                    status: 'N',
                    approve_explain: value
                  }
                  setOptLoading(true);
                  auditingRef?.current?.onSign({ sign_no: record.approval_id, sign_string: JSON.stringify(data), title: '批次审批' }, async () => {
                    await approveAccept(data).then(res => {
                      showMsg('已审批', MsgType.SUCCESS);
                      actionRef.current?.reload();
                      setAgreeVisible(false);
                      setLine(-1);
                      setOptLoading(false);
                    }).catch((error) => {
                      setOptLoading(false);
                      console.log('error', error);
                      showMsg(error?.data?.errmsg);
                    })
                  });

                }} />}
              trigger="click">

              <Auditing
                ref={auditingRef}
                loading={loading}
                module='I'
                onLoading={e => setLoading(e)}
                onError={() => {
                  setOptLoading(false);
                }}
                onClick={() => {
                  setAgreeVisible(true);
                  setLine(index);
                }}
                _html={<a>审批通过</a>}
              />
            </Popover>
          </PermissionControl>,

          <PermissionControl key="reject" action_id="200203003">
            <Popover
              visible={rejectVisible && line === index}
              // onVisibleChange={setRejectVisible}
              placement="topRight"
              content={<PopoverContent
                confirmText="审批拒绝"
                onCancel={() => {
                  setRejectVisible(false);
                  setLine(-1);
                }}
                loading={optLoading}
                onConfirm={async (value: string) => {
                  setOptLoading(true);
                  const data = {
                    approval_id: record.approval_id || '',
                    status: 'D',
                    approve_explain: value
                  }
                  auditingRef?.current?.onSign({ sign_no: record.approval_id, sign_string: JSON.stringify(data), title: '批次审批' }, async () => {
                    await approveReject(data).then(res => {
                      showMsg('已审批', MsgType.SUCCESS);
                      actionRef.current?.reload();
                      setRejectVisible(false);
                      setOptLoading(false);
                      setLine(-1);
                    }).catch(error => {
                      setOptLoading(false);
                      showMsg(error?.data?.message);
                    });
                  }
                  );
                }} />}
              trigger="click">
              <Auditing
                ref={auditingRef}
                loading={loading}
                module='I'
                onLoading={e => setLoading(e)}
                onError={() => {
                  setOptLoading(false);
                }}
                onClick={() => {
                  setRejectVisible(true);
                  setLine(index);
                }}
                _html={<a>审批拒绝</a>}
              />
            </Popover>
          </PermissionControl>
        ];
      }
    }
  ];


  // 按表单筛选项查询
  const forFormSearch = () => {
    setViewParams({});
    formRef.current?.submit();
  }

  // 商品规格
  const fetchGoodsSpecsList = async (goods_id: string) => {
    try {
      const data: STOCKGOODSAPI.GoodsSpecsItemList = await getGoodsSpecsList({ goods_id, current: 1, pageSize: 10000 });
      setGgList(data.record_list || []);
    } catch (error) {
      console.log('error', error)
      showMsg(error?.data?.errmsg);
    }
  }

  useEffect(() => {
    formRef.current?.setFieldsValue({
      create_date: [subtractDays(30), '', currentDate()]
    });
    formRef.current?.submit();
  }, []);

  // 点击查看
  const onView = () => {
    if (formRef.current) {
      // formRef.current.setFieldsValue({
      //   status: 'W'
      // });
      setViewParams({
        status: 'W'
      })
      formRef.current.submit();
    }
  }

  // @ts-ignore
  const onUploadChange = ({ file, fileList }) => {
    if (file.status === 'uploading') {
      setLoading(true);
    } else if (file.status === 'done') {
      setLoading(false);
      message.success(`${file.name} 导入成功`);
      actionRef.current?.reload();
    } else if (file.status === 'error') {
      setLoading(false);
      console.log('file', file, fileList)
      showMsg(file.response.errmsg);
    }
  }

  const download = async () => {
    setLoading(true);
    await downStockAdjustList(searchParams).then(res => {
      setLoading(false);
      window.open(`/api/report/${res.file_token}/down`);
    }).catch(res => {
      setLoading(false);
    });
  }

  return <>
    <ProTable<STOCKGOODSAPI.StockItem, STOCKGOODSAPI.StockItem & STOCKGOODSAPI.GoodsItem & { begin_date?: string; end_date?: string; } & COMMON.PageParams>
      actionRef={actionRef}
      rowKey="approval_id"
      bordered
      className="stock-pro-table mytable"
      formRef={formRef}
      manualRequest={true}
      loading={loading}
      search={{
        span: 8,
        collapsed: false,
        collapseRender: () => { return null },
        optionRender: (searchConfig, formProps, dom) => {
          return [
            <PermissionControl key="search" action_id="200203000">
              <Button
                onClick={() => {
                  forFormSearch()
                }}
                type="primary">
                查询
              </Button>
            </PermissionControl>,
            <PermissionControl action_id="200203001">
              <Button key="export" type="primary" loading={loading} disabled={!canDownload} onClick={download}>导出报表</Button>
            </PermissionControl>
          ]
        }
      }}

      request={async (params) => {
        console.log('params', params);
        if (params.create_date) {
          params.begin_date = params.create_date[0] && formatDate(params.create_date[0], 'YYYYMMDD');
          params.end_date = params.create_date[2] && formatDate(params.create_date[2], 'YYYYMMDD');
        }
        for (const prop in params) {
          if (!params[prop]) {
            delete params[prop];
          }
        }

        // @ts-ignore
        if (params.create_date[0] && params.create_date[2]) {
          // @ts-ignore
          if (getDateValue(params.create_date[0]) > getDateValue(params.create_date[2])) {
            showMsg('创建结束时间不能小于开始时间', MsgType.INFO);
            return {
              data: [],
              success: true,
              total: 0
            };
          }
        }
        delete params.create_date;
        if (viewParams.status) {
          params = {
            status: viewParams.status,
            current: params.current,
            pageSize: params.pageSize
          }
        }
        setSearchParams(params);
        try {
          const data: STOCKGOODSAPI.StockItemList = await getStockAdjustList(params);
          setWaitNum(data.wait_num);
          // @ts-ignore
          setCanDownload(data.record_list?.length > 0)
          return {
            data: data.record_list,
            success: true,
            total: data.sum_record_num
          };
        } catch (error) {
          showMsg(error?.data?.errmsg);
          return {
            data: [],
            success: true,
            total: 0
          };
        }
      }}
      rowClassName={(record) => {
        return record.approval_id === clickRow ? 'tableRowClick' : ''
      }}
      onRow={record => {
        return {
          onClick: event => { setClickRow(record.approval_id) }, // 点击行
          onMouseEnter: event => { }, // 鼠标移入行
          onMouseLeave: event => { },
        };
      }}

      rowSelection={{
        columnWidth: 30,
        onChange: (selectedRowKeys) => {
          setSelectedRowKeys(selectedRowKeys);
        },
        getCheckboxProps: (record) => {
          let disabled = false
          if (status === 'I') {
            disabled = ['D', 'W'].includes(record.status as string)
          } else {
            disabled = ['N', 'D'].includes(record.status as string)
          }
          return {
            disabled
          }
        }
      }}
      options={false}
      columns={columns}
      scroll={{
        scrollToFirstRowOnChange: true,
        // x: window.innerWidth < 1400 ? 1200 : null,
        x: 1100,
      }}
      toolBarRender={() => [<div>
        <div key="opt" style={{ display: 'flex' }}>
          {
            !isMobile &&
            <PermissionControl action_id="200203002">
              <Button
                style={{ height: '28px', lineHeight: '26px' }} type="primary"
                onClick={() => history.push('/stock-goods/stock/adjust-stock', { tab })}
              >
                调整库存
              </Button>
            </PermissionControl>
          }
          {
            isExits('200203003') &&
            <div style={{
              border: '1px solid #D8D8D8',
              display: 'flex',
              height: 28,
              alignItems: 'center',
              marginLeft: isMobile ? 0 : 10,
              padding: '0 2px'
            }}>

              <Select size='small' style={{ minWidth: '150px !important' }} className="stock-select" onChange={(value: string) => {
                actionRef.current?.clearSelected?.();
                setSelectedRowKeys([]);
                setStatus(value);
              }} dropdownMatchSelectWidth={false} defaultValue={isMobile ? "N" : "I"}>
                {
                  !isMobile && <Select.Option value="I">入库</Select.Option>
                }
                <Select.Option value="N">审批通过</Select.Option>
                <Select.Option value="D">审批拒绝</Select.Option>
              </Select>

              {
                (status === 'N' || status === 'D') ? <Popover
                  content={<PopoverContent confirmText={status === 'N' ? '审批通过' : '审批拒绝'} onConfirm={async (value: string) => {
                    try {
                      if (selectedRowKeys.length === 0) {
                        showMsg('请选择记录', MsgType.INFO);
                        return;
                      }
                      const data = {
                        approval_id: selectedRowKeys,
                        status,
                        approve_explain: value
                      }
                      await batchApprove(data);
                      showMsg('已审批', MsgType.SUCCESS);
                      // @ts-ignore
                      actionRef.current?.clearSelected();
                      actionRef.current?.reload();
                    } catch (error) {
                      showMsg(error?.data?.errmsg);
                    }
                  }} />}
                  trigger="click"
                  key="agree">
                  <Button
                    style={{ marginLeft: 10, height: '24px' }}
                    type="primary"

                  >
                    批量操作
                  </Button>
                </Popover> : <Upload
                  disabled={loading}
                  name="file"
                  action="/api/inventory/batch/approval/upload"
                  onChange={onUploadChange}
                  showUploadList={false}
                  beforeUpload={() => { message.loading('请稍后', 2) }}
                  headers={{ 'Oper-Token': localStorage.getItem('Oper-Token') as string, 'Action_Id': '200203003' }}
                >
                  <span style={{ padding: '3px 8px', lineHeight: '18px', background: '#096dd9', fontSize: 12, marginLeft: 10, color: '#fff', display: 'inline-block', borderRadius: '3px', cursor: 'pointer' }}>
                    批量操作
                    <Tooltip
                      placement="bottomRight"
                      title={
                        <a
                          href={downloadAddr}
                          target="_blank"
                          style={{ color: '#fff' }}
                          onClick={e => e.stopPropagation()}
                        >
                          下载模版
                        </a>
                      }
                    >
                      <DownloadOutlined style={{ marginLeft: 10 }} />
                    </Tooltip>
                  </span>
                </Upload>
              }
            </div>
          }
        </div>
        {waitNum > 0 && <TableHint
          key="tablehint"
          text={<div>有 <span style={{ color: '#F2232C', fontWeight: 'bold' }}>{waitNum}</span> 条记录待审批，点击查看。</div>}
          onAction={() => {
            onView();
          }}
          showAction />}
      </div>]
      }
      pagination={{
        showQuickJumper: true
      }}
    />
  </>;
};

export default ManageTab;

interface ManageTabProps {
  tab: string
  classList: COMMON.SelectOption[]
  brandList: COMMON.SelectOption[]
  goodsList: COMMON.SelectOption[]
}
